package client.service;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import client.io.ClientIO;
import domain.action.Action;
import domain.exception.ValidationException;
import domain.session.Request;
import domain.session.Response;
import domain.user.SystemUser;
import domain.user.User;

public class UserService {

	public static List<User> findUsers(String text) {
		JSONObject requestJson = new JSONObject();
		requestJson.put("query", text);
		ClientIO.sendRequest(new Request(Action.FIND_USERS, requestJson));

		Response response = ClientIO.getResponse();
		JSONObject responseJson = response.getResponse();
		JSONArray userArray = requestJson.getJSONArray("users");
		List<User> users = new ArrayList<User>();
		for (int i = 0; i < userArray.length(); i++) {
			users.add((User) userArray.getJSONObject(i));
		}
		return users;
	}

	public static Integer getUserId(String username) {
		JSONObject requestJson = new JSONObject();
		requestJson.put("username", username);
		ClientIO.sendRequest(new Request(Action.GET_USER_ID, requestJson));
		Response response = ClientIO.getResponse();
		JSONObject responseJson = response.getResponse();
		return responseJson.getInt("userId");
	}

	public static boolean thisIsValidUsername(String username) {
		JSONObject requestJson = new JSONObject();
		requestJson.put("username", username);
		ClientIO.sendRequest(new Request(Action.IS_VALID_USERNAME, requestJson));
		Response response = ClientIO.getResponse();
		return response.isSuccessful();
	}

	public static SystemUser getUser(Integer userId) {
		JSONObject requestJson = new JSONObject();
		requestJson.put("userId", userId);
		ClientIO.sendRequest(new Request(Action.GET_USER, requestJson));
		Response response = ClientIO.getResponse();
		JSONObject responseJson = response.getResponse();
		return new SystemUser(responseJson);
	}

	public static void modifyName(int userId, String nameFirst, String nameMiddle,
			String nameLast) throws ValidationException {
		JSONObject requestJson = new JSONObject();
		requestJson.put("userId", userId);
		requestJson.put("nameFirst", nameFirst);
		requestJson.put("nameMiddle", nameMiddle);
		requestJson.put("nameLast", nameLast);
		ClientIO.sendRequest(new Request(Action.MODIFY_NAME, requestJson));
		Response response = ClientIO.getResponse();
		JSONObject responseJson = response.getResponse();
		
		if (!response.isSuccessful()) {
			throw new ValidationException(responseJson.getString("msg"));
		}
		
	}

	public static void setActive(int userId, boolean b) {
		JSONObject requestJson = new JSONObject();
		requestJson.put("userId", userId);
		requestJson.put("active", b);
		ClientIO.sendRequest(new Request(Action.SET_ACTIVE, requestJson));
		Response response = ClientIO.getResponse();
	}

	public static int addUser(SystemUser user, String username, String p1,
			String p2) throws ValidationException {
		JSONObject requestJson = new JSONObject();
		requestJson.put("user", user.getJSON());
		requestJson.put("username", username);
		
		/**
		 * Encrypts the given password using SHA-256.
		 */			
		try { 
			byte[] p1Byte = p1.getBytes("ASCII");
			MessageDigest digest = MessageDigest.getInstance("SHA-256");
			digest.update(p1Byte);
			requestJson.put("p1", new String(digest.digest(), "ASCII")); 
			byte[] p2Byte = p1.getBytes("ASCII");
			digest.update(p2Byte);
			requestJson.put("p2", new String(digest.digest(), "ASCII")); 
		} catch (UnsupportedEncodingException ue) {
			ue.printStackTrace(); 
		} catch (NoSuchAlgorithmException ne) {
			ne.printStackTrace();
		}
		
		ClientIO.sendRequest(new Request(Action.ADD_USER, requestJson));
		Response response = ClientIO.getResponse();
		JSONObject responseJson = response.getResponse();
		if (!response.isSuccessful()) {
			throw new ValidationException(responseJson.getString("msg"));
		}
		
		return responseJson.getInt("userId");
	}

}
